<template>
  <div class="admin-manage-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>管理员管理</span>
          <el-button type="primary" @click="showAddDialog">添加管理员</el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="输入用户名搜索" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </el-form-item>
      </el-form>

      <!-- 管理员表格 -->
      <el-table :data="tableData" border style="width: 100%" v-loading="loading">
        <el-table-column prop="username" label="用户名" width="150" />
        <el-table-column prop="email" label="邮箱" width="468" />
        <el-table-column prop="gender" label="性别" width="200" />
        <el-table-column prop="role" label="角色" width="200">
          <template #default="{ row }">
            <el-tag :type="row.role === 2 ? 'danger' : 'primary'">
              {{ row.role === 2 ? '超级管理员' : '管理员' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createtime" label="创建时间" width="180" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button
                size="small"
                type="danger"
                @click="handleDelete(row)"
                :disabled="row.role === 2"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[5, 10, 20]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="fetchData"
          @current-change="fetchData"
      />

      <!-- 添加/编辑对话框 -->
      <el-dialog
          v-model="dialog.visible"
          :title="dialog.isEdit ? '编辑管理员' : '添加管理员'"
          width="500px"
      >
        <el-form
            :model="dialog.form"
            :rules="rules"
            ref="formRef"
            label-width="100px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="dialog.form.username" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="dialog.form.email" />
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="dialog.form.gender">
              <el-radio label="男" />
              <el-radio label="女" />
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="!dialog.isEdit" label="密码" prop="password">
            <el-input v-model="dialog.form.password" type="password" show-password />
          </el-form-item>
          <el-form-item v-if="!dialog.isEdit" label="确认密码" prop="confirmPassword">
            <el-input v-model="dialog.form.confirmPassword" type="password" show-password />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus';
import userApi from '../api/mockData/user.ts';

const formRef = ref<FormInstance>();
const tableData = ref([]);
const loading = ref(false);

// 搜索表单
const searchForm = reactive({
  username: ''
});

// 分页
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
});

// 对话框
const dialog = reactive({
  visible: false,
  isEdit: false,
  form: {
    id: '',
    username: '',
    email: '',
    gender: '男',
    password: '',
    confirmPassword: ''
  }
});

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在3到20个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在6到20个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value !== dialog.form.password) {
          callback(new Error('两次输入密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
};

// 获取数据
const fetchData = async () => {
  try {
    loading.value = true;
    const res = await userApi.getAdminList({
      username: searchForm.username,
      page: pagination.current,
      size: pagination.size
    });
    tableData.value = res.data.records;
    pagination.total = res.data.total;
  } catch (error) {
    ElMessage.error('获取数据失败');
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.current = 1;
  fetchData();
};

// 显示添加对话框
const showAddDialog = () => {
  dialog.visible = true;
  dialog.isEdit = false;
  resetForm();
};

// 显示编辑对话框
const handleEdit = (row: any) => {
  dialog.visible = true;
  dialog.isEdit = true;
  dialog.form = {
    ...row,
    password: '',
    confirmPassword: ''
  };
};

// 重置表单
const resetForm = () => {
  dialog.form = {
    id: '',
    username: '',
    email: '',
    gender: '男',
    password: '',
    confirmPassword: ''
  };
};

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value?.validate();

    if (dialog.isEdit) {
      await userApi.updateAdmin(dialog.form.id, {
        username: dialog.form.username,
        email: dialog.form.email,
        gender: dialog.form.gender
      });
      ElMessage.success('管理员更新成功');
    } else {
      await userApi.addAdmin({
        username: dialog.form.username,
        email: dialog.form.email,
        gender: dialog.form.gender,
        password: dialog.form.password
      });
      ElMessage.success('管理员添加成功');
    }
    dialog.visible = false;
    fetchData();
  } catch (error) {
    ElMessage.error('操作失败: ' + (error as Error).message);
  }
};

// 删除
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(`确定删除管理员 ${row.username} 吗?`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    await userApi.deleteAdmin(row.id);
    ElMessage.success('管理员删除成功');
    fetchData();
  } catch (error) {
    // 用户取消删除不做任何操作
  }
};

// 初始化
onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.admin-manage-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
</style>